package com.jinglvhuanjing.app.base;


import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import androidx.appcompat.widget.AppCompatTextView;


import java.lang.ref.WeakReference;

public abstract class CountDownActivity extends InstructionActivity{
    protected Handler mHandler;
    protected int mSecond = 60;
    protected MyRunnable mRunnable;
    protected AppCompatTextView mCountText;

    public abstract void initCountDownText();

    public abstract void countDownComplete();

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        this.initCountDownText();
        this.mHandler = new Handler(Looper.myLooper());
        this.mRunnable = new MyRunnable(this);
        this.mHandler.post(this.mRunnable);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.mHandler.removeCallbacks(this.mRunnable);
        this.mRunnable = null;
    }

    private static class MyRunnable implements Runnable{
        private WeakReference<CountDownActivity> weakReference;
        private MyRunnable(CountDownActivity activity){
            weakReference = new WeakReference<>(activity);
        }
        @Override
        public void run() {
            CountDownActivity activity =  weakReference.get();
            if(activity == null){
                return;
            }
            if(activity.mSecond <= 0){
                activity.mHandler.removeCallbacks(this);
                activity.countDownComplete();
                return;
            }
            activity.mCountText.setText(String.format("%ss" ,--activity.mSecond));
            activity.mHandler.postDelayed(this , 1000);
        }
    }
}
